Fortran For Fun 之GUI编程gtk-fortran

GTK+是一个功能强大,设计灵活的通用GUI编程库,(与其类似的库还有Qt),可以利用这个库创建图形界面程序,使用较为简单。

gtk是使用C语言编写的,提供各种语言的API, 包括Fortran语言的API.gtk_fortran,利用该接口,可以使用Fortran语言创建图形界面程序。

learn_gtk_fortran

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
program learn_gtk_button
use handlers, only:hello, quit
use iso_c_binding
use gtk, only: gtk_init, gtk_window_new, GTK_WINDOW_TOPLEVEL, gtk_widget_show_all, gtk_main, &
& gtk_vbox_new, gtk_button_new_with_label, gtk_box_pack_start, g_signal_connect, FALSE, TRUE, &
& GTK_ORIENTATION_HORIZONTAL, gtk_container_add
implicit none
type(c_ptr) :: window, box, button, button2
call gtk_init()
!> window
window = gtk_window_new (GTK_WINDOW_TOPLEVEL)
!> box
box = gtk_vbox_new (TRUE, _c_int);
call gtk_container_add (window, box)
!> button
button = gtk_button_new_with_label ("Run"//c_null_char)
call gtk_box_pack_start (box, button, FALSE, FALSE, _c_int)
call g_signal_connect (button, "clicked"//c_null_char, c_funloc(hello))
!> button2
button2 = gtk_button_new_with_label ("Quit"//c_null_char)
call gtk_box_pack_start (box, button2, FALSE, FALSE, _c_int)
call g_signal_connect (button2, "clicked"//c_null_char, c_funloc(quit))
call gtk_widget_show_all (window)
call gtk_main ()
end program learn_gtk_button
module handlers
use gtk, only: gtk_main_quit, FALSE
implicit none
contains
! "clicked" is a GtkButton signal
function hello (widget, gdata ) result(ret) bind(c)
use iso_c_binding, only: c_ptr, c_int
integer(c_int) :: ret
type(c_ptr), value :: widget, gdata
print *, "Hello World!"
ret = FALSE
end function hello
! "quit" is a GtkObject signal
subroutine quit (widget, gdata) bind(c)
use iso_c_binding, only: c_ptr
type(c_ptr), value :: widget, gdata
print *, "Exit program"
call gtk_main_quit ()
end subroutine quit
end module handlers

结果

以上程序会创建一个窗口,有Run和Quit两个按钮,点击Run会输出’Hello World!’,点击Quit,直接退出程序。
hdf5_view